package com.uzai.console.service.md.mdgoods.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.enums.MdActivityStatusEnum;
import com.uzai.common.enums.MdRobotCmdKeyEnum;
import com.uzai.common.enums.PlatformTypeEnum;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.dto.feign.turnlink.SimpleTurnLinkDto;
import com.uzai.console.dto.feign.turnlink.TbPrivilegeDto;
import com.uzai.console.dto.md.mdactivity.MdActivityCopyDto;
import com.uzai.console.dto.md.mdactivity.MdActivityDto;
import com.uzai.console.dto.md.mdactivity.MdActivityIdDto;
import com.uzai.console.dto.md.mdactivity.MdActivityQuery;
import com.uzai.console.dto.md.mdgoods.*;
import com.uzai.console.dto.tb.tbapi.TbkScTpwdConvertDto;
import com.uzai.console.entity.*;
import com.uzai.console.mapper.*;
import com.uzai.console.service.feign.UzaiBusinessFeignService;
import com.uzai.console.service.feign.UzaiTurnlinkFeignService;
import com.uzai.console.service.md.mdactivity.MdActivityService;
import com.uzai.console.service.md.mdexchange.MdExchangeService;
import com.uzai.console.service.md.mdgoods.ExemptionGoodsService;
import com.uzai.console.service.md.mdrebotcmd.MdRobotCmdService;
import com.uzai.console.service.tb.tbapi.TbApiService;
import com.uzai.console.vo.feign.turnlink.SimpleTurnlinkVo;
import com.uzai.console.vo.md.exemptiongoods.ExemptionGoodsVo;
import com.uzai.console.vo.md.mdactivity.MdActivityCopyUrlVo;
import com.uzai.console.vo.md.mdactivity.MdActivityVo;
import com.uzai.console.vo.md.mdgoods.MdGoodsTurnlinkVo;
import com.uzai.console.vo.md.mdgoods.MdGoodsVo;
import com.uzai.console.vo.pyq.llygoods.PyqLlyGoodsVo;
import com.uzai.console.vo.tb.tbapi.TbkScTpwdConvertVo;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 免单活动
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class ExemptionGoodsServiceImpl implements ExemptionGoodsService {

    Logger logger = LoggerFactory.getLogger(ExemptionGoodsServiceImpl.class);

    @Autowired
    private MdActivityMapper mdActivityMapper;
    @Autowired
    private UzaiBusinessFeignService uzaiBusinessFeignService;
    @Autowired
    private MdConfigPlanMapper mdConfigPlanMapper;
    @Autowired
    private MdRobotCmdService mdRobotCmdService;
    @Autowired
    private MdRobotCmdMapper mdRobotCmdMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MdExchangeService mdExchangeService;

    /**
     * 查询官方商品列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param mdGoodsQuery
     * @return null
     */
    public Page<ExemptionGoodsVo> findExemptionGoodsList(MdGoodsQuery mdGoodsQuery){
        //返回到页面分页对象
        Page<ExemptionGoodsVo> pageVo = new Page<>();
        ExemptionGoodsQuery exemptionGoodsQuery = new ExemptionGoodsQuery();
        BeanUtils.copyProperties(mdGoodsQuery, exemptionGoodsQuery);
        //默认淘宝平台
        exemptionGoodsQuery.setPlatformType(Tools.getInteger(mdGoodsQuery.getPlatform()));
        UzaiRespVo<Page<ExemptionGoodsVo>> uzaiRespVo =  uzaiBusinessFeignService.findPageByMdExemptionGoods(exemptionGoodsQuery);
        //logger.info("---调用免单官方商品库查询--para={},result={}", JSONObject.toJSONString(llyGoodsPageDto),JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo.getCode() == 200){
            Page<ExemptionGoodsVo> exemptionGoodsVoPage =  uzaiRespVo.getData();
            if(exemptionGoodsVoPage != null){
                BeanUtils.copyProperties(exemptionGoodsVoPage, pageVo);
                List<ExemptionGoodsVo> exemptionGoodsVoList =  exemptionGoodsVoPage.getRecords();
                if(exemptionGoodsVoList != null && exemptionGoodsVoList.size() > 0){
                    for (ExemptionGoodsVo exemptionGoodsVo : exemptionGoodsVoList) {
                        //获取已付款数量
                        Integer payedAmount = mdExchangeService.countPayOrderWithGoodsId(exemptionGoodsVo.getId(), null, mdGoodsQuery.getMerId());
                        exemptionGoodsVo.setPayedAmount(Tools.getInteger(payedAmount));
                    }
                }
                pageVo.setRecords(exemptionGoodsVoList);
            }
        }
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询默认的免单官方活动
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param mdActivityQuery
     * @return null
     */
    public MdActivityVo findMdActivityByDefault(MdActivityQuery mdActivityQuery){
        //新建返回到页面的LIST对象
        MdActivityVo mdActivityVo = new MdActivityVo();
        //默认查询官方活动
        mdActivityQuery.setSource(1);
        //执行分页查询对象
        Page<MdActivity> page = new Page<>();
        mdActivityQuery.convert(page);
        ArrayList<MdActivity> mdActivityList =  mdActivityMapper.findByList(page, mdActivityQuery);
        if(mdActivityList != null && mdActivityList.size() > 0){
            MdActivity mdActivity = mdActivityList.get(0); //默认取第一个
            BeanUtils.copyProperties(mdActivity, mdActivityVo);
            //免单指令转化成list
            if(StringUtils.isNotBlank(mdActivity.getCommands())){
                try {
                    mdActivityVo.setCommandList(JSONObject.parseArray(mdActivity.getCommands(), String.class));
                }catch (Exception e){

                }
            }

            //活动状态
            Integer status = Tools.getInteger(mdActivity.getStatus());
            //开始时间
            Integer startTime = Tools.getInteger(mdActivity.getStartTime());
            //结束时间
            Integer endTime = Tools.getInteger(mdActivity.getEndTime());

            if(mdActivityVo.getStatus() != null){
                MdActivityStatusEnum mdActivityStatusEnum = MdActivityStatusEnum.getById(mdActivityVo.getStatus());
                if(mdActivityStatusEnum != null){
                    mdActivityVo.setStatusName(mdActivityStatusEnum.getDesc());
                }
            }

            //配置方案
            MdConfigPlan mdConfigPlan = mdConfigPlanMapper.selectById(mdActivity.getConfigId(), mdActivity.getMerId());
            if(mdConfigPlan != null){
                mdActivityVo.setConfigName(mdConfigPlan.getName());
                if(mdConfigPlan.getData() != null){
                    try {
                        //活动场景（0-群组活动；1-私聊活动）
                        JSONObject jsonObject = JSONObject.parseObject(mdConfigPlan.getData());
                        mdActivityVo.setActivityScenes(jsonObject.getInteger("activityScenes"));
                    }catch (Exception e){

                    }
                }
            }

            //触发指令
            String commands = mdActivity.getCommands();
            if(StringUtils.isNotBlank(commands)){
                try {
                    List<String> commandList = JSONObject.parseArray(commands, String.class);
                    mdActivityVo.setCommandList(commandList);
                }catch (Exception e){

                }
            }

            //会员标签
            String userTags = mdActivity.getUserTags();
            if(StringUtils.isNotBlank(userTags)){
                try {
                    List<Long> userTagsList = JSONObject.parseArray(userTags, Long.class);
                    mdActivityVo.setUserTagsList(userTagsList);
                }catch (Exception e){

                }
            }
        }
        return mdActivityVo;
    }


    /**
     * 添加免单活动
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param mdActivityDto
     * @return null
     */
    @Transactional
    public void addMdActivity(MdActivityDto mdActivityDto){
        //查询官方免单活动是否已经存在
        MdActivityQuery mdActivityQuery = new MdActivityQuery();
        mdActivityQuery.setMerId(mdActivityDto.getMerId());
        mdActivityQuery.setSource(1);//官方活动
        //执行分页查询对象
        Page<MdActivity> page = new Page<>();
        ArrayList<MdActivity> mdActivityList =  mdActivityMapper.findByList(page, mdActivityQuery);
        if(mdActivityList != null && mdActivityList.size() > 0) {
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "官方活动已经存在，不能再次添加");
        }

        //活动类型
        Integer activityType = Tools.getInteger(mdActivityDto.getActivityType());
        //活动名称
        String name = Tools.getStr(mdActivityDto.getName());
        if(StringUtils.isBlank(name)){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入活动名称");
        }
        //活动图片
        String imgUrl = mdActivityDto.getImgUrl();
//        if(StringUtils.isBlank(imgUrl)){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入活动图片");
//        }
        //触发指令
        List<String> commandList = mdActivityDto.getCommandList();
        //配置方案
        Long configId = mdActivityDto.getConfigId();
        if(configId == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择配置方案");
        }

        Integer now = DateUtil.getNowTime();

        MdActivity mdActivity = new MdActivity();
        BeanUtils.copyProperties(mdActivityDto, mdActivity);
        //查询数据库最大得活动id
        Long maxActivityId = mdActivityMapper.findMaxActivityId();
        if(maxActivityId != null){ //数据库有，则递增+1
            maxActivityId = maxActivityId + 1;
        }else{ //数据库没有，则默认等于10000
            maxActivityId = 10000L;
        }
        //状态
        if(Tools.getInteger(mdActivityDto.getJoinStatus()).intValue() == 0 ){ //不不开启，将活动状态设置为暂停
            mdActivity.setStatus(MdActivityStatusEnum.PAUSE.getValue());
        }else{
            mdActivity.setStatus(MdActivityStatusEnum.NOT_START.getValue());  //参与活动，将活动状态设置为未开始
        }

        mdActivity.setId(IdWorker.getId());
        mdActivity.setSource(1);//官方活动
        mdActivity.setMerId(mdActivityDto.getMerId());
        mdActivity.setActivityId(maxActivityId);
        //触发指令
        mdActivity.setCommands(Tools.getStrEmpty(JSONObject.toJSONString(commandList)));
        //会员标签
        mdActivity.setUserTags(Tools.getStrEmpty(JSONObject.toJSONString(mdActivityDto.getUserTagsList())));
        mdActivity.setCreateTime(now);
        mdActivity.setUpdateTime(now);
        mdActivityMapper.insertSelective(mdActivity);

        //增加免单唤醒指令
        mdRobotCmdService.addMdRobotCmdForMdAtivity(mdActivityDto.getMerId(), mdActivity.getId(), MdRobotCmdKeyEnum.WAKEUPCMD.getKey(), commandList);
        //更新指令redis缓存
        List<MdRobotCmd> mdRobotCmdList = mdRobotCmdMapper.selectByMerId(mdActivityDto.getMerId());
        String data = Tools.getStrEmpty(JSONObject.toJSONString(mdRobotCmdList));
        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.MD_COMMAND_LIST.getKey(), mdActivityDto.getMerId()), data, 30, TimeUnit.DAYS);
    }

    /**
     * 修改免单活动
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param mdActivityDto
     * @return null
     */
    @Transactional
    public void updateMdActivity(MdActivityDto mdActivityDto){

        int now = DateUtil.getNowTime();

        if(mdActivityDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        if(StringUtils.isBlank(mdActivityDto.getName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入活动名称");
        }

        //配置方案
        Long configId = mdActivityDto.getConfigId();
        if(configId == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择配置方案");
        }

        MdActivity mdActivity = mdActivityMapper.selectById(mdActivityDto.getId(), mdActivityDto.getMerId());

        if(mdActivity == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该官方活动不存在");
        }

        //修改免单
        mdActivity.setSource(1); //官方活动
        mdActivity.setName(mdActivityDto.getName());
        mdActivity.setImgUrl(mdActivityDto.getImgUrl());
        mdActivity.setActivityType(mdActivityDto.getActivityType());
        mdActivity.setCommands(Tools.getStrEmpty(JSONObject.toJSONString(mdActivityDto.getCommandList())));
        //会员标签
        mdActivity.setUserTags(Tools.getStrEmpty(JSONObject.toJSONString(mdActivityDto.getUserTagsList())));
        mdActivity.setConfigId(configId);
        mdActivity.setAwardModel(mdActivityDto.getAwardModel());
        mdActivity.setAmoygoldType(mdActivityDto.getAmoygoldType());
        mdActivity.setLimitHours(mdActivityDto.getLimitHours());
        mdActivity.setLimitTimes(mdActivityDto.getLimitTimes());
        mdActivity.setStartTime(mdActivityDto.getStartTime());
        mdActivity.setEndTime(mdActivityDto.getEndTime());
        mdActivity.setUpdateTime(now);
        //状态
        if(Tools.getInteger(mdActivityDto.getJoinStatus()).intValue() == 0 ){ //不不开启，将活动状态设置为暂停
            mdActivity.setStatus(MdActivityStatusEnum.PAUSE.getValue());
        }else{
            mdActivity.setStatus(MdActivityStatusEnum.NOT_START.getValue());  //参与活动，将活动状态设置为未开始
        }
        int j = mdActivityMapper.updateById(mdActivity);

        //修改成功
        if(j == 1){
            //添加免单触发唤醒指令
            List<String> commandList = mdActivityDto.getCommandList();
            //增加免单唤醒指令
            mdRobotCmdService.addMdRobotCmdForMdAtivity(mdActivityDto.getMerId(), mdActivity.getId(), MdRobotCmdKeyEnum.WAKEUPCMD.getKey(), commandList);
            //更新指令redis缓存
            List<MdRobotCmd> mdRobotCmdList = mdRobotCmdMapper.selectByMerId(mdActivityDto.getMerId());
            String data = Tools.getStrEmpty(JSONObject.toJSONString(mdRobotCmdList));
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.MD_COMMAND_LIST.getKey(), mdActivityDto.getMerId()), data, 30, TimeUnit.DAYS);
        }
    }


    /**
     * 删除
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param mdActivityIdDto
     * @return null
     */
    @Transactional
    public void deleteMdActivity(MdActivityIdDto mdActivityIdDto){
        if(mdActivityIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        MdActivity mdActivity = mdActivityMapper.selectById(mdActivityIdDto.getId(), mdActivityIdDto.getMerId());
        if(mdActivity == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该活动不存在");
        }

        mdActivityMapper.deleteById(mdActivityIdDto.getId(), mdActivityIdDto.getMerId());

        //删除指令
        mdRobotCmdMapper.deleteByActivityId(mdActivity.getId(), mdActivity.getMerId());

        //更新指令redis缓存
        List<MdRobotCmd> mdRobotCmdList = mdRobotCmdMapper.selectByMerId(mdActivityIdDto.getMerId());
        String data = Tools.getStrEmpty(JSONObject.toJSONString(mdRobotCmdList));
        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.MD_COMMAND_LIST.getKey(), mdActivityIdDto.getMerId()), data, 30, TimeUnit.DAYS);
    }

    /**
     * 暂停免单活动
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param mdActivityIdDto
     * @return null
     */
    public void pauseMdActivity(MdActivityIdDto mdActivityIdDto){
        if(mdActivityIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        MdActivity mdActivity = mdActivityMapper.selectById(mdActivityIdDto.getId(), mdActivityIdDto.getMerId());

        if(mdActivity == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该免单活动不存在");
        }

        mdActivity.setStatus(MdActivityStatusEnum.PAUSE.getValue()); //暂停
        Integer now = DateUtil.getNowTime();
        mdActivity.setUpdateTime(now);
        mdActivityMapper.updateById(mdActivity);
    }

    /**
     * 开启免单活动
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param mdActivityIdDto
     * @return null
     */
    public void startMdActivity(MdActivityIdDto mdActivityIdDto){
        if(mdActivityIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        MdActivity mdActivity = mdActivityMapper.selectById(mdActivityIdDto.getId(), mdActivityIdDto.getMerId());

        if(mdActivity == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该免单活动不存在");
        }

        mdActivity.setStatus(MdActivityStatusEnum.START.getValue()); //开启
        Integer now = DateUtil.getNowTime();
        mdActivity.setStartTime(now);
        mdActivity.setUpdateTime(now);
        mdActivityMapper.updateById(mdActivity);
    }

}
